package com.wbw.linux;


import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.*;

public class executePython {
    public static void executePython() throws Exception {
        Connection conn = new Connection("192.168.45.3", 22);
        conn.connect();
        boolean b = conn.authenticateWithPassword("root", "wbw4132443");
        if (b) {
            try {
                Session session = conn.openSession();
                session.requestPTY("bash");
                session.startShell();
                PrintWriter out = new PrintWriter(session.getStdin());
                out.println("cd / && ls \n");
                out.println("ls");
                out.println("exit"); //不可省略，否则readline不结束
                out.close();
                System.out.println("ExitStatus " + session.getExitStatus()); //null
                System.out.println("State: " + session.getState()); //2,session运行中

                //StreamGobbler的作用是把session的标准输出包装成InputStream，用于接收目标服务器上的控制台返回结果。自带缓冲区
                InputStream stdout = new StreamGobbler(session.getStdout());
                InputStream stderr = new StreamGobbler(session.getStderr());
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
                //BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
                int i = session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, 3000);
                // i = 1 超时
                String line;
                while ((line = stdoutReader.readLine()) != null) {
                    System.out.println(line);
                }
                /* Show exit status, if available (otherwise "null") */
                session.close();
                System.out.println("ExitStatus: " + session.getExitStatus()); //0或者null表示会话结束了
                System.out.println("State: " + session.getState());
                conn.close();
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        executePython();
    }

}

